import config from './config.js'
const request = (
    // uview Toast的指向this(弃用)
    that = {},
    // 请求地址和请求方式
    urlType = {
        url: '',
        type: 'GET',
    },
    // 请求参数
    data = {}, 
    // 头部信息
    header = {
        "Content-Type": "application/json",
        Authorization: urlType.isAuthorization == false ? '' : uni.getStorageSync("Authorization")
    }
) => {
    return new Promise((resolve, reject) => {
        // const baseUrl = uni.getStorageSync("baseUrl") ? uni.getStorageSync("baseUrl") : 'http://220.171.59.122:8083/'
        uni.request({
            method: urlType.type,
            // url: baseUrl + urlType.url,
            url: config.baseUrl + urlType.url,
            data: data,
            header: header,
            dataType: 'json',
        }).then((response) => {
            let [ error,res ] = response
            // console.log('请求成功', res, error)
            uni.hideLoading()
            if ( res && res.statusCode == 200 ){
                if ( res.data.code == 200 ) {
                    if (urlType.paging){
                        resolve( res.data )
                    }else{
                        resolve( res.data.data ? res.data.data : res.data )
                    }
                } else if ( res.data.code == 401) {
                    uni.$u.toast('登陆过期,即将重新登陆',1500)
                    setTimeout(() => {
                        uni.reLaunch({ url: '/pages/login/login' })
                    }, 1500);
                } else {
                    console.log(res)
                    uni.$u.toast(res.data.msg);
                }
            }else{
                uni.$u.toast(res ? res.errMsg : error.errMsg)
            }
        }).catch(error => {
            let [err, res] = error
            // console.log('请求失败', res, err)
            uni.hideLoading()
            reject(err)
        })
    });
}
export default request